package com.sgb.merchant.view.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.IndustryCategoryEntity;
import com.sgb.link.entity.merchant.IndustryListEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivitySelfIndustryListBinding;
import com.sgb.merchant.view.adapter.SelfIndustryListAdapter;
import com.sgb.merchant.viewmodel.IndustryViewModel;
import com.sgb.merchant.widget.SelectTypeWindow;
import com.sgb.net.entity.ListResponse;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 王彬臣
 * @date: 2021/10/14
 * @Description: 我的产业园区列表
 */
@Route(path = PathMerchant.SelfIndustryListActivity)
public class SelfIndustryListActivity extends BaseActivity<IndustryViewModel, MerchantActivitySelfIndustryListBinding> {

    private boolean mIsLoadMore;
    private boolean mIsHasSearch;
    Map<String, Object> mMap = new HashMap<>();
    int selectPos;
    SelfIndustryListAdapter mAdapter;
    List<IndustryListEntity> mList = new ArrayList<>();
    List<IndustryCategoryEntity> mLeveList = new ArrayList<>();
    List<IndustryCategoryEntity> mTypeList = new ArrayList<>();
    List<IndustryCategoryEntity> mStatusList = new ArrayList<>();

    SelectTypeWindow mLevePop, mTypePop, mStatusPop;
    private boolean isChange1, isChange2, isChange3;
    private String leveTypeName,typeName,statusName;

    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_self_industry_list;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(IndustryViewModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.setClick(this);
        mBinding.displayView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new SelfIndustryListAdapter(mList);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ARouter.getInstance().build(PathMerchant.SelfIndustryDetailActivity).withString(RouterKey.NO, mList.get(position).getNo()).navigation();

            }
        });
        mAdapter.setClickBtnListener(new SelfIndustryListAdapter.ClickBtnListener() {
            @Override
            public void putAway(String no, int position) {
                selectPos = position;
                mViewModel.getDetailState(SelfIndustryListActivity.this, no, 1);

            }

            @Override
            public void dowAway(String no, int position) {
                selectPos = position;
                mViewModel.getDetailState(SelfIndustryListActivity.this, no, 2);
            }

            @Override
            public void editClick(String no, int position) {
                selectPos = position;
                mViewModel.getDetailState(SelfIndustryListActivity.this, no, 0);
            }

            @Override
            public void delClick(String no, int position) {
                selectPos = position;
                mViewModel.getDetailState(SelfIndustryListActivity.this, no, 3);
            }
        });

        mAdapter.bindToRecyclerView(mBinding.displayView);
        mAdapter.setEmptyView(R.layout.merchant_empty_views);
        mBinding.displayView.setAdapter(mAdapter);
        mBinding.refreshLayout.setEnableRefresh(true);
        mBinding.refreshLayout.setEnableLoadMore(true);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refreshData(true);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData(false);
            }
        });
        initWindowPop();
        initEvent();
        initData();
    }

    private void initData() {
        mViewModel.ldData.observe(this, this::showProjectList);
        mViewModel.ldLeve.observe(this, data -> {
            IndustryCategoryEntity entity = new IndustryCategoryEntity("不限", "");
            data.add(0, entity);
            mLeveList.addAll(data);
            mLevePop.setData(data);
            mLevePop.showPopwindow0(mBinding.llChoose);
        });
        mViewModel.ldType.observe(this, data -> {
            IndustryCategoryEntity entity = new IndustryCategoryEntity("不限", "");
            data.add(0, entity);
            mTypeList.addAll(data);
            mTypePop.setData(data);
            mTypePop.showPopwindow0(mBinding.llChoose);
        });
        mViewModel.ldStatus.observe(this, result -> {
            if (!result) {
                new RoundDialog.Builder(this)
                        .title("温馨提示")
                        .content("该数据状态已发生变化，请刷新后再进行操作。")
                        .cancel("取消")
                        .confirm("确定")
                        .cancelable(false)
                        .confirmCallback(v12 -> refreshData(false)).show();
            }else{
                refreshData(false);
            }
        });
        mViewModel.ldDoResult.observe(this, success -> {
            IndustryListEntity entity = mList.get(selectPos);
            if (entity.getStatus().equals("0")) {
                entity.setStatus("1");
            } else {
                entity.setStatus("0");
            }
            mAdapter.notifyDataSetChanged();
        });
        mViewModel.ldDel.observe(this, success -> {
            mList.remove(selectPos);
            mAdapter.notifyDataSetChanged();
        });
        mBinding.tvLeve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(leveTypeName)){
                    mBinding.tvLeve.updateChooseTextStatus(-2, leveTypeName);
                }else {
                    mBinding.tvLeve.updateChooseTextStatus(-2, mBinding.tvLeve.getKeyName());
                }
                if (mLeveList.size() == 0) {
                    mViewModel.getLevel();
                } else {
                    mLevePop.showPopwindow0(mBinding.popLine);
                }
            }
        });
         mBinding.tvStatusType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(statusName)){
                     mBinding.tvStatusType.updateChooseTextStatus(-2, statusName);
                }else {
                     mBinding.tvStatusType.updateChooseTextStatus(-2,  mBinding.tvStatusType.getKeyName());
                }


                mStatusPop.showPopwindow0(mBinding.llChoose);
            }
        });
        mBinding.tvTypes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(typeName)){
                    mBinding.tvTypes.updateChooseTextStatus(-2, typeName);
                }else {
                    mBinding.tvTypes.updateChooseTextStatus(-2, mBinding.tvTypes.getKeyName());
                }
                if (mTypeList.size() == 0) {
                    mViewModel.getType();
                } else {
                    mTypePop.showPopwindow0(mBinding.llChoose);
                }
            }
        });
        DialogHelper.showProgressDialog(this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        refreshData(false);
    }

    private void initWindowPop() {
        mLevePop = new SelectTypeWindow(this);
        mLevePop.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                isChange1 = true;
                IndustryCategoryEntity mEntity = (IndustryCategoryEntity) key1;
                leveTypeName= mEntity.getCategoryName();
                mBinding.tvLeve.updateChooseTextStatus(1, mEntity.getCategoryName());
                mMap.put("assistantSectionLevelNo", mEntity.getCategoryNo());

                refreshData(false);
            }
        });
        mLevePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (isChange1) {
                    mBinding.tvLeve.updateChooseTextStatus(1, null);
                }else{
                    mBinding.tvLeve.updateChooseTextStatus(0, mBinding.tvLeve.getKeyName());
                }
            }
        });
        mTypePop = new SelectTypeWindow(this);
        mTypePop.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                isChange2 = true;
                IndustryCategoryEntity mEntity = (IndustryCategoryEntity) key1;
                typeName=mEntity.getCategoryName();
                mBinding.tvTypes.updateChooseTextStatus(1, mEntity.getCategoryName());
                mMap.put("parkTypeNo", mEntity.getCategoryNo());
                refreshData(false);
            }
        });
        mTypePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (isChange2) {
                    mBinding.tvTypes.updateChooseTextStatus(1, null);
                }else{
                    mBinding.tvTypes.updateChooseTextStatus(0, mBinding.tvTypes.getKeyName());
                }

            }
        });

        mStatusPop = new SelectTypeWindow(this);
        mStatusPop.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                isChange3 = true;
                IndustryCategoryEntity mEntity = (IndustryCategoryEntity) key1;
                statusName=mEntity.getCategoryName();
                 mBinding.tvStatusType.updateChooseTextStatus(1, mEntity.getCategoryName());
                mMap.put("parkStatus", mEntity.getCategoryNo());
                refreshData(false);
            }
        });
        mStatusPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (isChange3) {
                     mBinding.tvStatusType.updateChooseTextStatus(1, null);
                }else{
                     mBinding.tvStatusType.updateChooseTextStatus(0,  mBinding.tvStatusType.getKeyName());
                }

            }
        });
        IndustryCategoryEntity mStatus = new IndustryCategoryEntity("不限", "");
        IndustryCategoryEntity mStatus1 = new IndustryCategoryEntity("上架", "1");
        IndustryCategoryEntity mStatus2 = new IndustryCategoryEntity("下架", "0");
        mStatusList.add(mStatus);
        mStatusList.add(mStatus1);
        mStatusList.add(mStatus2);
        mStatusPop.setData(mStatusList);
    }


    private void initEvent() {
        mBinding.ivCloseRed.setOnClickListener(v -> {
            mBinding.editSearchRed.setText("");
            if (mIsHasSearch) {
                DialogHelper.showProgressDialog(this, "搜索中").setCanceledOnTouchOutside(true);
                closeKeybord();
                mMap.remove("likeParkName");
                refreshData(false);
            }
        });
        mBinding.editSearchRed.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mBinding.editSearchRed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                closeKeybord();
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    mIsHasSearch = true;
                    if (TextUtils.isEmpty(mBinding.editSearchRed.getText().toString())) {
                        MToast.showToast(SelfIndustryListActivity.this, "请输入园区名称");
                        return true;
                    }
                    DialogHelper.showProgressDialog(SelfIndustryListActivity.this, "搜索中").setCanceledOnTouchOutside(true);
                    mMap.put("likeParkName", mBinding.editSearchRed.getText().toString());
                    refreshData(false);
                }
                return false;
            }
        });
        mBinding.editSearchRed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mBinding.ivCloseRed.setVisibility(View.GONE);
                } else {
                    mBinding.ivCloseRed.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void refreshData(boolean mIsLoadMore) {
        this.mIsLoadMore = mIsLoadMore;
        mViewModel.getSelfInvestmentData(mIsLoadMore, mMap);

    }

    public void showProjectList(ListResponse<List<IndustryListEntity>> entity) {
        mBinding.refreshLayout.finishRefresh();
        mBinding.refreshLayout.finishLoadMore();
        if (entity == null) {
            return;
        }
        if (!mIsLoadMore) {
            mList.clear();
        }
        if (entity.getList() != null) {
            mList.addAll(entity.getList());
        }

        mAdapter.notifyDataSetChanged();


        //
        if (entity.getCurrentPage() < entity.getTotalPage()) {
            mIsLoadMore = true;
            mBinding.refreshLayout.resetNoMoreData();
        } else {
            mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back_red) {
            finish();

        } else if (v.getId() == R.id.tv_search) {
            if (mBinding.editSearchRed.getText().toString().equals("")) {
                MToast.showToast(this, "请输入入园名称");
                return;
            }
            DialogHelper.showProgressDialog(this, "搜索中").setCanceledOnTouchOutside(true);
            mIsHasSearch = true;
            mMap.put("likeParkName", mBinding.editSearchRed.getText().toString());
            closeKeybord();
            refreshData(false);
        } else if (v.getId() == R.id.tv_publish) {
            ActivityJump.startActivity(PathMerchant.ActivityPublishParks);
        }
    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MainEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_REFRESH) {
            refreshData(false);
        }
    }
}
